<?php
/**
 * description...
 *
 * @author Tinyhu
 * @package SimpleController
 */
class UcenterController extends Controller
{

    public $layout='index';
    public $safebox = null;
    private $model = null;
    private $category = array();
    private $cookie_time = 31622400;
    public  $sidebar = array(
        
        '个人信息'=>array(
            '个人资料'=>'info',
            '收货地址'=>'address',
            
        ),
        '会员管理'=>array(
            '注册会员'=>'reg_user',
            '我的推广'=>'my_user',
            //'推广图谱'=>'my_tjr',
        ),
        '账户管理'=>array(
            '账户金额'=>'account',
            //'我的积分'=>'point',
            //'我的优惠券'=>'voucher',
            '修改密码'=>'password_change',
            '申请开通'=>'sq_ckordp',
            
        ),
        
        /*
        '爱心互助'=>array(
            '申请资助'=>'application_support',
            '我的担保'=>'myisdb_list',
            '我的资助'=>'help_list',
        ),
        */
        /*
        '积分交易'=>array(
            '交易大厅' => 'transaction_list',
            '我的交易' => 'my_transaction',
        ),
        */
        '财务管理'=>array(
            '充值扣款' => 'recharge_list',
            //'转账记录' => '',
            //'兑换记录' => 'exchange_list',
            '提现记录' => 'withdraw_list',
            //'转账记录' => 'zz_list',
            '奖金明细' => 'jjmx_list',
        ),
        
        '订单管理'=>array(
            '我的订单'=>'order',
            '退款申请'=>'refund',
            // '退货申请'=>'returns',
            '我的关注'=>'attention',
        ),
        '客户服务'=>array(
            '商品咨询'=>'consult',
            '商品评价'=>'review',
            '我的消息'=>'message',
            '在线留言'=>'ask',
        ),
        
    );

    public function init()
    {
        header("Content-type: text/html; charset=".$this->encoding);
        $this->model = new Model();
        $this->safebox =  Safebox::getInstance();
        $this->user = $this->safebox->get('user');
        if($this->user==null){
            $this->user = Common::autoLoginUserInfo();
            $this->safebox->set('user',$this->user);
        }
        if ($this->user['is_seller']==1) {
            $this->sidebar['店铺管理']=
                array(
                    //'我的店铺'=>'my_dp',
                    // '销售详情'=>'sell_list',
                    '添加商品'=>'goods_edit',
                    '店铺商品'=>'goods_list',
                    '销售订单'=>'sell_order_list',
                );
        }
        
        $category = Category::getInstance();

        $this->category = $category->getCategory();
        $cart = Cart::getCart();
        $action = Req::args("act");
        switch ($action) 
        {
            case 'order_detail':
                $action = 'order';
                break;
            case 'refund_detail':
                $action = 'refund';
                break;
        }
        $this->assign("actionId",$action);
        $this->assign("cart",$cart->all());
        $this->assign("sidebar",$this->sidebar);
        $this->assign("category",$this->category);
        $this->assign("seo_title","用户中心");
        $model = new Model();
        //$user_obj = $model->table("user")->join("inner join zyk_customer on user.id=zyk_customer.user_id")->where("user_id=".$this->user[id])->find();
        $user_obj = $model->query("select zyk_user.*,zyk_customer.* from zyk_user,zyk_customer where zyk_user.id=zyk_customer.user_id and zyk_user.id=".$this->user[id]);
        $user_obj = $user_obj[0];
        $this->assign("user", $user_obj);
        
        //$this->redirect("/simple/reg");
        
    }

    public function checkRight($actionId)
    {
        if(isset($this->user['name']) && $this->user['name']!=null) return true;
        else return false;
    }
    public function noRight()
    {
        $this->redirect("/simple/login");
    }

    public function withdraw()
    {
        Filter::form();
        $account   = floatval(Req::args('account'));
        $name      = Filter::txt(Req::args('name'));
        $type_name = Filter::txt(Req::args('type_name'));
        $account   = Filter::txt(Req::args('account'));
        $amount    = Filter::float(Req::args('amount'));
        $pass2     = Filter::txt(Req::args('pass2'));
        
        $tx_flag = intval( Common::getConfigJjsetValue("jjset_txflag") );
        if($tx_flag === 0)
        {
            $info = array('status'=>'fail','msg'=>'提现功能暂时还不能操作');
            echo JSON::encode($info);
            die;
        }
        
        $txf       = $amount*(Common::getConfigJjsetValue('jjset_txf')/100);
        $sj_money  = $amount-$txf;

        $model    = new Model('customer');
        $customer = $model->where("user_id=".$this->user['id'])->find();
        if (Common::getPass2($this->user['id'],$pass2)==0) 
        {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
            echo JSON::encode($info);
            die;
        }
        
        if($amount < 100 || $amount % 10 != 0)
        {
            $info = array('status'=>'fail','msg'=>'提现金额必须大于等于100且为10的倍数');
            echo JSON::encode($info);
            die;
        }
        
        if($customer['balance'] < $amount)
        {
            $info = array('status'=>'fail','msg'=>'提现金额超出账户余额');
        }
        else
        {
            $obj  = $model->table("withdraw")->where("status=0 and user_id=".$this->user['id'])->find();
            if($obj)
            {
                $info = array('status'=>'fail','msg'=>'上次申请的提现，还未处理，处理后才可再申请。');
            }
            else
            {
                $model->table("customer")->where("user_id=".$this->user['id'])->data(array('balance'=>"`balance`-$amount"))->update();
                $data = array('name'=>$name,'type_name'=>$type_name,'account'=>$account,'txf'=>$txf,'sq_money'=>$amount,'amount'=>$sj_money,'time'=>date('Y-m-d H:i:s'),'user_id'=>$this->user['id']);
                $model->table("withdraw")->data($data)->insert();
                $info = array('status'=>'success','msg'=>'申请成功.');
            }
        }
        echo JSON::encode($info);
    }
    
    //转换
    public function zh()
    {
        Filter::form();
        //转换类型
        $zh_type  = intval( Filter::int(Req::args('zh_type')) );
        //$zh_get = Filter::txt(Req::args('zh_get'));
        $amount   = floatval( Filter::txt(Req::args('amount')) );
        $pass2    = Filter::txt(Req::args('pass2'));
        $model    = new Model();
        $user_id  = $this->user['id'];
        $user_obj = Common::get_user_obj($user_id);        
        
        
        if($zh_type === 0 && !Common::is_not_allow_do_by_time())
        {
            $info = array('status'=>'fail','msg'=>'此时不允许执行该操作');
            echo JSON::encode($info);
            die;
        }
        
        
        if( Common::getPass2($user_id, $pass2) == 0)
        {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
            echo JSON::encode($info);
            die;
        }
        
        if($zh_type < 3)
        {
            if($amount < 1)
            {
                $info = array('status'=>'fail','msg'=>'兑换金额最低不能小于1');
                echo JSON::encode($info);
                die;
            }    
        }
        else
        {
            if($amount < 100 || $amount % 100 != 0)
            {
                $info = array('status'=>'fail','msg'=>'兑换金额最低不能为100，且为100的倍数');
                echo JSON::encode($info);
                die;
            }
        }
        //兑换类型
        switch($zh_type)
        {
            case 0:
                $zh_from_account_type = 'balance';
                $zh_to_account_type   = 'voucher';
                $desc                 = "账户余额 兑换 消费券";
                break;
            case 1:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'voucher';
                $desc                 = "通用积分 兑换 消费券";
                break;
            case 2:
                $zh_from_account_type = 'currency_point';
                $zh_to_account_type   = 'ok_xfjf';
                $desc                 = '通用积分 兑换 可用积分';
                break;
            case 3:
                $zh_from_account_type = 'ok_xfjf';
                $zh_to_account_type   = 'currency_point';
                $desc                 = '可用积分 兑换 通用积分';
                break;
        }
        
        /**
         * 如果账户余额不足
         */
        $ye = $user_obj[$zh_from_account_type];
        if($amount > $ye)
        {
            $info = array('status'=>'fail','msg'=>'余额不足');
            echo JSON::encode($info);
            die;
        }
        
        $from_amount = $amount;
        $to_amount   = $amount;
        
        $fbf = 0;
        /**
         * 可用积分 兑换 通用积分
         */
        if($zh_type === 3)
        {
            $fbf_bili    = Common::getConfigJjsetValue("jjset_fbf")/100;
            $fbf         = $amount * $fbf_bili;
            $to_amount   = $amount - $fbf;
            
            $data['fbf'] = $fbf;
        }
        
        
        $model->query("start transaction");
        
        $result1 = $model->table("customer")->data([$zh_from_account_type=>"`$zh_from_account_type`-$from_amount",$zh_to_account_type=>"`$zh_to_account_type`+$to_amount"])->where("user_id=$user_id")->update();
        $data['user_id'] = $user_id;
        
        $data['zh_lx']    = $zh_type;
        $data['zh_desc']  = $desc;
        //兑换金额
        $data['zh_money'] = $from_amount;
        //实际到帐金额
        $data['real_money'] = $to_amount;
        $data['zh_time']  = date('Y-m-d H:i:s');
        $result2 = $model->table("zh")->data($data)->insert();
        
        if($zh_type === 0)
        {
            $from_info = $user_obj['name'].'账户余额 兑换 消费券';
        }
        elseif($zh_type === 1)
        {
            $from_info = $user_obj['name'].'通用积分 兑换 消费券';
        }
        //产生各种奖金  账户余额兑换消费券的时候财产生各种奖金，同时升级，同时保存每日新增业绩
        //账户余额兑换消费券  和通用积分兑换消费券  这2个操作都产生奖金
        if($zh_type === 0 || $zh_type === 1)
        {
            //产生奖金
            Jjjs::exec_all_jj($user_id, $amount, $from_info);
            //根据消费总金额，判断是否升级为合格会员
            //添加每日新增业绩
            Jjjs::sj_and_save_xzyj($user_id, $amount, $from_info);
        }
        
        
        if($result1 && $result2)
        {
            //提交事务
            $model->query("commit");
            $info = array('status'=>'success','msg'=>'操作成功');
            echo JSON::encode($info);
            die;
        }
        else
        {
            //回滚事务
            $model->query("rollback");
            $info = array('status'=>'fail','msg'=>'操作失败');
            echo JSON::encode($info);
            die;
        }
        
        /*
        $mc_f=Common::getBzName($zh_from);
        $mc_g=Common::getBzName($zh_get);
        $cx_suoding=Common::getConfigJjsetValue("jjset_cx_sd");
        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->user['id'])->find();
        
        if (Common::getPass2($this->user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
        }elseif($customer[$zh_from]<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }elseif($zh_from=='cx' && $customer['cx']-$cx_suoding<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }else
        {
            $ye=$customer[$zh_from]-$amount;
            if ($zh_get=='gwb') 
            {
                $uget=$customer[$zh_get]+$amount*3;
            }
            elseif ($zh_get=='xxb') 
            {
                $uget=$customer[$zh_get]+$amount*2;
            }
            else
            {
                $uget=$customer[$zh_get]+$amount;
            }
            $model->where("user_id=".$this->user['id'])->data(array($zh_from=>"`$zh_from`-$amount",$zh_get=>$uget))->update();
            $data = array('user_id'=>$this->user['id'],'ye'=>$ye,'zh_lx'=>$mc_f." → ".$mc_g,'zh_money'=>$amount,'zh_time'=>date('Y-m-d H:i:s'));
            $model->table("zh")->data($data)->insert();
            $info = array('status'=>'success','msg'=>'转换成功.');
        }
        
        echo JSON::encode($info);
        */
        /*
        Filter::form();
        $zh_from = Filter::txt(Req::args('zh_from'));
        $zh_get = Filter::txt(Req::args('zh_get'));
        $amount = Filter::txt(Req::args('amount'));
        $pass2 = Filter::txt(Req::args('pass2'));
        $mc_f=Common::getBzName($zh_from);
        $mc_g=Common::getBzName($zh_get);
        $cx_suoding=Common::getConfigJjsetValue("jjset_cx_sd");
        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->user['id'])->find();

        if (Common::getPass2($this->user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
        }elseif($customer[$zh_from]<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }elseif($zh_from=='cx' && $customer['cx']-$cx_suoding<$amount){
            $info = array('status'=>'fail','msg'=>'转换金额超出'.$mc_f.'余额');
        }else{
            $ye=$customer[$zh_from]-$amount;
            if ($zh_get=='gwb') {
                $uget=$customer[$zh_get]+$amount*3;
            }elseif ($zh_get=='xxb') {
                $uget=$customer[$zh_get]+$amount*2;
            }else{
                $uget=$customer[$zh_get]+$amount;
            }
            $model->where("user_id=".$this->user['id'])->data(array($zh_from=>"`$zh_from`-$amount",$zh_get=>$uget))->update();
            $data = array('user_id'=>$this->user['id'],'ye'=>$ye,'zh_lx'=>$mc_f." → ".$mc_g,'zh_money'=>$amount,'zh_time'=>date('Y-m-d H:i:s'));
            $model->table("zh")->data($data)->insert();
            $info = array('status'=>'success','msg'=>'转换成功.');
        }

        echo JSON::encode($info);
        */
    }
    //转账
    public function zz()
    {
           
        //用户转账的账户类型,通用积分
        $zz_account_type = "currency_point";
        //Filter::form();
        //接受用户
        $toname = Filter::txt(Req::args('zz_toname'));
        $amount = Filter::float(Req::args('zz_amount'));
        $pass2 = Filter::txt(Req::args('zz_pass2'));
        $bz = Filter::txt(Req::args('zz_bz'));
        
        $from_user_id = intval(Req::args('hid_zz_from_user_id'));
        
        $validate_code = Req::args('validate_code');//短信验证码
        
        
            $u=$this->model->table("user")->where("name='$toname'")->find();
            if ($u) {
                
                
                /********短信验证码检测模块*********/
                $model = new Model();
                $uname = $this->user['name'];
                //判断短信验证码是否正确
                $sms_code_obj = $model->table("sms_code")->where("mobile='{$uname}' and sms_code='{$validate_code}' and sms_is_used=0")->find();
                if(empty($sms_code_obj))
                {
                    $info = array('status'=>'fail','msg'=>'手机短信验证码不正确！');
                    echo JSON::encode($info);
                    die;
                }
                else
                {
                    if(strtotime($sms_code_obj['sms_close_time']) < time())
                    {
                        $info = array('status'=>'fail','msg'=>'验证码已过期，请重新获取！');
                        echo JSON::encode($info);
                        die;
                    }
                }
                
                
                $toid=$u['id'];
                //$from_user_id = intval($this->user['id']);
                if($from_user_id === intval($toid))
                {
                    $info = array('status'=>'fail','msg'=>'不能给自己转账！');
                    echo JSON::encode($info);
                    die;
                }
                
                //$model = $this->model->table("user as us");
                $model = new Model();
                //$obj = $model->join("left join customer as cu on us.id = cu.user_id")->where("user_id=".$this->user['id'])->find();
                $obj = Common::get_user_obj($from_user_id);
                if ($obj) {
                    if (Common::getPass2($this->user['id'],$pass2)!=0) {
                        if ($amount>$obj[$zz_account_type]) 
                        {
                            $info = array('status'=>'fail','msg'=>'余额不足！');
                        }
                        else
                        {
                            $this->model->table("customer")->data(array($zz_account_type=>"`$zz_account_type`-$amount"))->where("user_id=".$this->user['id'])->update();
                            $this->model->table("customer")->data(array($zz_account_type=>"`$zz_account_type`+$amount"))->where("user_id=".$toid)->update();
                            
                            $data = array('bz'=>$bz,'lx'=>$zz_account_type,'uname'=>$obj['name'],'je'=>$amount,'time'=>date('Y-m-d H:i:s'),'toname'=>$toname);
                            
                            //转出用户id
                            $data['from_user_id'] = $this->user['id'];
                            
                            //转入用户id
                            $data['to_user_id']   = $toid;
                            
                            $this->model->table("zz")->data($data)->insert();
                            
                            //修改短信验证码状态
                            $result4 = $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
                            
                            $info = array('status'=>'success','msg'=>'转账成功！');
                        }
                    }else{
                        $info = array('status'=>'fail','msg'=>'交易密码错误！');
                    }
                }
            }else{
                $info = array('status'=>'fail','msg'=>'接收人不存在，请核实！');
            }

        echo JSON::encode($info);

    }

    //添加资助额
    public function jk_add()
    {
        Filter::form();
        $dbr = Filter::txt(Req::args('dbr'));
        $sq_je = Filter::float(Req::args('sq_je'));
        $pass2 = Filter::txt(Req::args('pass2'));
        $dbr_sf = Common::getUname($dbr)['gd_ok'];//担保人股东身份
        $dbr_id = Common::getUname($dbr)['id'];//担保人id
        $ck_sf = Common::getUid($this->user['id'])['u_lx'];//担保人id
        $dk_lx = (Common::getConfigJjsetValue('dk_lx')/100)*$sq_je;
        $dk_qx = Common::getConfigJjsetValue('dk_qx');

        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->user['id'])->find();
        if ($ck_sf==0) {
            $info = array('status'=>'fail','msg'=>'您目前还不是创客，无法申请！');
        }elseif($dbr_sf==0){
            $info = array('status'=>'fail','msg'=>'担保人不是股东，无法作担保！');
        }elseif($dbr_id==$this->user['id']){
            $info = array('status'=>'fail','msg'=>'申请人不能作为担保人');
        }elseif($sq_je<Common::getConfigJjsetValue('dk_qdje')){
            $info = array('status'=>'fail','msg'=>'申请金额不能小于最低额度');
        }elseif (Common::getPass2($this->user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
        }elseif($customer['xyb']<30000){
            $info = array('status'=>'fail','msg'=>'您的信用币不够申请！');
        }else{
            $kxyb=$sq_je*0.2;
            $model->where("user_id=".$this->user['id'])->data(array('xyb'=>"`xyb`-$kxyb"))->update();
            $data = array('sq_id'=>$this->user['id'],'lx_money'=>$dk_lx,'qx'=>$dk_qx,'h_money'=>$dk_lx+$sq_je,'dbr_id'=>$dbr_id,'sq_money'=>$sq_je,'sq_time'=>date('Y-m-d H:i:s'));
            $model->table("pd")->data($data)->insert();
            $info = array('status'=>'success','msg'=>'申请成功.');
        }

        echo JSON::encode($info);

    }
    //取消资助申请
    function zzsq_del()
    {
        $id = Req::args("id");
        $model = new Model("pd");
        $pdinfo=$model->where("pd_id = $id")->find();
        $zt=$pdinfo['is_ok'];
        $txyb=$pdinfo['sq_je']*0.2;
        $uid=$pdinfo['sq_id'];
        if ($uid==$this->user['id']) {
            if ($zt<2) {
                $model->where("pd_id = $id")->delete();
                $modell->table("pd")->where("user_id=".$this->user['id'])->data(array('xyb'=>"`xyb`+$txyb"))->update();
            }
        }
        $this->redirect("application_support");
    }
    //担保人审核
    function zzsq_shisok()
    {
        $id = Req::args("id");
        $model = new Model("pd");
        $pdinfo=$model->where("pd_id = $id")->find();
        $zt=$pdinfo['is_ok'];
        $uid=$pdinfo['dbr_id'];
        if ($uid==$this->user['id']) {
            if ($zt==0) {
               $model->data(array('is_ok'=>1))->where("pd_id = $id")->update();
            }
        }
        $this->redirect("myisdb_list");
    }
    //还款页
    function zzsq_hk()
    {
        $id = Req::args("id");
        $model = new Model("pd");
        $p=$model->where("pd_id = $id")->find();
        $customer = $model->table("customer")->where("user_id=".$this->user['id'])->find();
        $this->assign("customer",$customer);
        $this->assign("p",$p);
        $this->redirect();
    }

    //还款
    public function hk_save()
    {
        Filter::form();
        $pd_id = Filter::txt(Req::args('pid'));
        $pass2 = Filter::txt(Req::args('pass2'));
        $model = new Model('pd');
        $pd = $model->where("pd_id=".$pd_id)->find();
        $hk_je=$pd['h_money'];
    if($pd['sq_id']==$this->user['id']){
        if($hk_je>Common::getC($pd['sq_id'])['balance']){
            $info = array('status'=>'fail','msg'=>'还款额度超出账户余额，请充值！');
        }elseif (Common::getPass2($this->user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确'.$pd_id);
        }else{
            $model->data(array('is_ok'=>3,'h_time'=>date('Y-m-d H:i:s')))->where("pd_id=".$pd_id)->update();
            $model->table("customer")->where("user_id=".$this->user['id'])->data(array('balance'=>"`balance`-$hk_je"))->update();
            $model->table("customer")->where("user_id=".$pd['fc_id'])->data(array('balance'=>"`balance`+$hk_je"))->update();
            $info = array('status'=>'success','msg'=>'已成功还款!');
            //写入账户变动日志
            Log::balance((0-$hk_je),$pd['sq_id'],"还款给资助人--[".Common::getC($pd['fc_id'])['real_name']."(".Common::getUid($pd['fc_id'])['name'].")] ");
            Log::balance($hk_je,$pd['fc_id'],"被资助人--[".Common::getC($pd['sq_id'])['real_name']."(".Common::getUid($pd['sq_id'])['name'].")] 到期还款");
        }
    }
        echo JSON::encode($info);

    }

    public function point()
    {
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $this->assign("customer",$customer);
        $this->redirect();
    }
    public function point_exchange()
    {
        $id = Filter::int(Req::args('id'));
        $voucher = $this->model->table("voucher_template")->where("id=$id")->find();
        if($voucher){
           $use_point = 0 - $voucher['point'];
            $result = Pointlog::write($this->user['id'], $use_point, '积分兑换代金券，扣除了'.$use_point.'积分');
            if(true===$result){
                Common::paymentVoucher($voucher,$this->user['id']);
                $info = array('status'=>'success');
            }else{
                $info = array('status'=>'fail','msg'=>$result['msg']);
            }
            echo JSON::encode($info);
        }else{
            $info = array('status'=>'fail','msg'=>'你要兑换的代金券，不存在！');
            echo JSON::encode($info);
        }
    }
    public function password_save()
    {
        if(!Tiny::app()->checkToken())$this->redirect("password_change");
        $lx = Req::post('lx');
        $oldpassword = Req::post('oldpassword');
        $password = Req::post('password');
        $repassword = Req::post('repassword');
        $obj = $this->model->table("user")->where("id=".$this->user['id'])->find();
        if($password && $password==$repassword){
            if($lx==1){
                if($obj['password'] == CHash::md5($oldpassword,$obj['validcode'])){
                    $validcode = CHash::random(8);
                    $data = array('password'=>CHash::md5($password,$validcode),'validcode'=>$validcode,'pass1'=>$password);
                    $obj = $this->model->table("user")->where("id=".$this->user['id'])->data($data)->update();
                    $this->redirect("password_change",false,array('msg'=>array("success","密码修改成功！")));
                }else{
                    $this->redirect("password_change",false,array('msg'=>array("fail","原密码不正确！")));
                }
            }elseif($lx==2){
                if($obj['passwordtwo'] == CHash::md5($oldpassword)){
                    $data = array('passwordtwo'=>CHash::md5($password),'pass2'=>$password);
                    $obj = $this->model->table("user")->where("id=".$this->user['id'])->data($data)->update();
                    $this->redirect("password_change",false,array('msg'=>array("success","密码修改成功！")));
                }else{
                    $this->redirect("password_change",false,array('msg'=>array("fail","原密码不正确！")));
                }
            }
        }else{
            $this->redirect("password_change",false,array('msg'=>array("fail","两次密码不一致！")));
        }

    }
    public function account()
    {
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $this->assign("customer",$customer);
        $this->redirect();
    }
    public function application_support()
    {
        // $uid=$this->user['id'];
        // $t=Zyk_tj::sum('pd','sq_money',"sq_id=$uid and is_ok>1");
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        // $this->assign("tj",$t);
        $this->assign("customer",$customer);
        $this->assign("dk_qdje",Common::getConfigJjsetValue('dk_qdje'));
        $this->redirect();
    }
    public function help_list()
    {
        $pid=Req::args('id');
        $pinfo=$this->model->table("pd")->where("pd_id=".$pid)->find();
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $this->assign("pinfo",$pinfo);
        $this->assign("customer",$customer);
        $this->redirect();
    }
    //帮助
    public function help_add()
    {
        Filter::form();
        $pid = Filter::int(Req::args('pid'));
        $pass2 = Filter::txt(Req::args('pass2'));
        $pinfo=$this->model->table("pd")->where("pd_id=".$pid)->find();
        $sq_je=$pinfo['sq_money'];
        $js_id=$pinfo['sq_id'];

        $model = new Model('customer');
        $customer = $model->where("user_id=".$this->user['id'])->find();
        if (Common::getPass2($this->user['id'],$pass2)==0) {
            $info = array('status'=>'fail','msg'=>'二级密码不正确');
        }elseif($customer['balance']<$sq_je){
            $info = array('status'=>'fail','msg'=>'您的账户余额不足！');
        }else{
            $model->where("user_id=".$this->user['id'])->data(array('balance'=>"`balance`-$sq_je"))->update();
            $model->where("user_id=".$js_id)->data(array('jkb'=>"`jkb`+$sq_je"))->update();
            $data = array('fc_id'=>$this->user['id'],'is_ok'=>2,'fc_time'=>date('Y-m-d H:i:s'));
            $model->table("pd")->data($data)->where("pd_id=".$pid)->update();
            //写入账户变动日志
            Log::balance((0-$sq_je),$this->user['id'],"资助给--[".Common::getC($pd['sq_id'])['real_name']."(".Common::getUid($pd['sq_id'])['name'].")] ");
            $info = array('status'=>'success','msg'=>'资助成功.');
        }

        echo JSON::encode($info);

    }
    public function ly_act()
    {
        
        Filter::form(array('question'));
        $data = array(
            'question'=>TString::nl2br(Req::args('question')),
            'ask_time'=>date('Y-m-d H:i:s'),
            'user_id'=>$this->user['id'],
            );
        $this->model->table("ly")->data($data)->insert();
        $this->redirect("ask",false,array('msg'=>array("success","留言成功,请等候回复！")));
                
    }
    public function refund_act()
    {
        $order_no = Filter::sql(Req::args('order_no'));
        $order = $this->model->table("order")->where("order_no='$order_no' and user_id = ".$this->user['id'])->find();
        if($order){
            if($order['pay_status']==1){
                $refund = $this->model->table("doc_refund")->where("order_no='$order_no' and user_id = ".$this->user['id'])->find();
                if($refund){
                    $this->redirect("refund",false,array('msg'=>array("warning","不能重复申请退款！")));
                }
                else{
                    Filter::form(array('text'=>'account_name|refund_account|account_bank|content','int'=>'order_no|refund_type'));
                    $data = array(
                        'account_name'=>Req::args('account_name'),
                        'refund_account'=>Req::args('refund_account'),
                        'account_bank'=>Req::args('account_bank'),
                        'order_no'=>Req::args('order_no'),
                        'refund_type'=>Req::args('refund_type'),
                        'create_time'=>date('Y-m-d H:i:s'),
                        'user_id'=>$this->user['id'],
                        'order_id'=>$order['id'],
                        'content'=>Req::args('content'),
                        'pay_status'=>0
                        );
                    $this->model->table("doc_refund")->data($data)->insert();
                     //改变订单的状态
                     $order_id = $order['id'];
                    $this->model->table("order")->data(array('pay_status'=>2))->where("id=$order_id")->update();
                    
                    $this->redirect("refund",false,array('msg'=>array("success","申请已经成功提交,请等候处理！")));
                }
            }else{
                $this->redirect("refund",false,array('msg'=>array("warning","此订单还未支付，无法申请退款！")));
            }

        }else{
            $this->redirect("refund",false,array('msg'=>array("warning","此订单编号不存在！")));
        }
    }
    
    public function refund_detail()
    {
        $id = Filter::int(Req::args('id'));
        $refund = $this->model->table("doc_refund")->where("id=$id and user_id=".$this->user['id'])->find();
        if($refund){
            $this->assign("refund",$refund);
            $this->redirect();
        }
        else{
            Tiny::Msg($this, 404);
        }
    }
    public function refund_del()
    {
        $order_no = Filter::sql(Req::args('order_no'));
        $obj = $this->model->table("doc_refund")->where("order_no='$order_no' and  pay_status=0 and user_id = ".$this->user['id'])->delete();
        $this->redirect("refund");
    }
    public function voucher_activated()
    {
        if(!Tiny::app()->checkToken())$this->redirect("voucher");
        $rules = array('account:required:账号不能为空!','password:required:密码不能为空！');
        $info = Validator::check($rules);
        if(!is_array($info) && $info==true) {
            Filter::form(array('sql'=>'account'));
            $account = Filter::sql(Req::args("account"));
            $voucher = $this->model->table("voucher")->where("account='$account' and is_send = 0")->find();
            if($voucher && $voucher['password'] == Req::args("password")){
                if(strtotime($voucher['end_time']) > time()){
                    if($voucher['status'] ==0){
                        $this->model->table("voucher")->data(array('user_id'=>$this->user['id'],'is_send'=>1,'status'=>0))->where("account='$account'")->update();
                        $this->redirect("voucher",false,array('msg'=>array("success","优惠券成功激活！")));
                    }else{
                        $this->redirect("voucher",false,array('msg'=>array("warning","此优惠券已使用过！")));
                    }
                }
                else{
                    //过期
                    $this->redirect("voucher",false,array('msg'=>array("warning","优惠券已过期！")));
                }

            }else{
                //不存在此优惠券
                 $this->redirect("voucher",false,array('msg'=>array("error","优惠券账号或密码错误！")));
            }
        }else{
            //输入信息有误
             $this->redirect("voucher",false,array('msg'=>array("info","输入的信息不格式不正确")));
        }
    }
    public function get_consult()
    {
        $page = Filter::int(Req::args("page"));
        $type = Filter::int(Req::args("type"));
        $status = Req::args("status");
        $where = "ak.user_id = ".$this->user['id'];
        switch ($status) {
            case 'n':
                $where .= " and ak.status = 0";
                break;
            case 'y':
                $where .= " and ak.status = 1";
                break;
            default:
                break;
        }
        $ask = $this->model->table("ask as ak")->join("left join goods as go on ak.goods_id = go.id")->fields("ak.*,go.name,go.id as gid,go.img,go.sell_price")->where($where)->order("ak.id desc")->findPage($page,10,$type,true);
        foreach ($ask['data'] as $key => $value) {
           $ask['data'][$key]['img'] = Common::thumb($value['img'],100,100);
        }
        $ask['status'] = "success";
        echo JSON::encode($ask);
    }
    //获取商品评价
    public function get_review()
    {
        $page = Filter::int(Req::args("page"));
        $type = Filter::int(Req::args("type"));
        $status = Req::args("status");
        $where = "re.user_id = ".$this->user['id'];
        switch ($status) {
            case 'n':
                $where .= " and re.status = 0";
                break;
            case 'y':
                $where .= " and re.status = 1";
                break;
            default:
                break;
        }
        $review = $this->model->table("review as re")->join("left join goods as go on re.goods_id = go.id")->fields("re.*,go.name,go.id as gid,go.img as img,go.sell_price")->where($where)->order("re.id desc")->findPage($page,10,$type,true);
        $data = $review['data'];
        foreach ($data as $key => $value) {
            $value['point'] = ($value['point']/5)*100;
            $data[$key] = $value;
        }
        $review['status'] = "success";
        $review['data'] = $data;
        echo JSON::encode($review);
    }
    //获取商品评价
    public function get_message()
    {
        $page = Filter::int(Req::args("page"));
        $type = Filter::int(Req::args("type"));
        $status = Req::args("status");
        $where = "";
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $message_ids = '';
        if($customer){
            $message_ids = ','.$customer['message_ids'].',';
            switch ($status) {
                case 'y':
                    $message_ids = preg_replace('/,\d+,/i', ',', $message_ids);
                    $message_ids = preg_replace('/-/i','',$message_ids);
                    break;
                case 'n':
                    $message_ids = preg_replace('/,-\d+,/i', ',', $message_ids);
                    break;
                default:
                    break;
            }
            $message_ids = trim($message_ids,',');
        }

        $message  = array();
        if($message_ids!=''){
            $message = $this->model->table("message")->where("id in ($message_ids)")->order("id desc")->findPage($page,10,$type,true);
        }
        $message['status'] = "success";
        echo JSON::encode($message);
    }

    public function message_read()
    {
        $id = Filter::int(Req::args("id"));
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $message_ids = ','.$customer['message_ids'].',';
        $message_ids = str_replace(",$id,",',-'.$id.',',$message_ids);
        $message_ids = trim($message_ids,',');
        $this->model->table("customer")->where("user_id=".$this->user['id'])->data(array('message_ids'=>$message_ids))->update();
        echo JSON::encode(array("status"=>'success'));
    }
    public function message_del()
    {
        $id = Filter::int(Req::args("id"));
        $customer = $this->model->table("customer")->where("user_id=".$this->user['id'])->find();
        $message_ids =','.$customer['message_ids'].',';
        $message_ids = str_replace(",-$id,",',',$message_ids);
        $message_ids = rtrim($message_ids,',');
        $this->model->table("customer")->where("user_id=".$this->user['id'])->data(array('message_ids'=>$message_ids))->update();
        echo JSON::encode(array("status"=>'success'));
    }
    public function get_voucher()
    {
        $page = Filter::int(Req::args("page"));
        $pagetype = Filter::int(Req::args("pagetype"));
        $status = Req::args("status");
        $where = "user_id = ".$this->user['id']." and is_send = 1";
        switch ($status) {
            case 'n':
                $where .= " and status = 0 and '".date("Y-m-d H:i:s")."' <=end_time";
                break;
            case 'u':
                $where .= " and status = 1";
                break;
            case 'p':
                $where .= " and status = 0 and '".date("Y-m-d H:i:s")."' > end_time";
                break;
            default:
                break;
        }
        $voucher = $this->model->table("voucher")->where($where)->order("id desc")->findPage($page,10,$pagetype,true);
        $data = $voucher['data'];
        foreach ($data as $key => $value) {
            $value['start_time'] = substr($value['start_time'],0,10);
            $value['end_time'] = substr($value['end_time'],0,10);
            $data[$key] = $value;
        }
        $voucher['data'] = $data;
        $voucher['status'] = "success";
        echo JSON::encode($voucher);
    }
    public function info()
    {
        $info = $this->model->table("customer as cu ")->fields("cu.*,us.email,us.name,gr.name as gname")->join("left join user as us on cu.user_id = us.id left join grade as gr on cu.group_id = gr.id")->where("cu.user_id = ".$this->user['id'])->find();
        if($info){
            $this->assign("info",$info);
            $info = array_merge($info,Req::args());
            $this->redirect("info",false,$info);
        }else Tiny::Msg($this, 404);

    }
    public function sq_ckordp()
    {
        //获得上一次的申请记录
        $user_id = $this->user['id'];
        $model = new Model();
        $list = $model->table("sq_list")->where("user_id=$user_id")->order("sq_id desc")->limit("1")->select();
        
        if(!empty($list))
        {
            $this->assign("sq_obj", $list[0]);
        }
        /*
        $uinfo = $this->model->table("customer")->where("user_id = ".$this->user['id'])->find();
        $dlinfo = $this->model->table("agent")->where("user_id = ".$this->user['id'])->find();
        $info = $this->model->table("dp")->where("user_id = ".$this->user['id'])->find();
        $this->assign("balance",$uinfo['balance']);
        $this->assign("ck",$uinfo['ck_ok']);
        $this->assign("dlinfo",$dlinfo);
        $this->assign("info",$info);
        $this->assign("dlinfo",$dlinfo);
        $this->assign("ckzhifu",Common::getConfigJjsetValue("jjset_ck_chongzhi"));
        $this->assign("xxb",Common::getConfigJjsetValue("jjset_xxb"));
        $this->assign("xyb",Common::getConfigJjsetValue("jjset_xyb"));
        $this->assign("gwb",Common::getConfigJjsetValue("jjset_gwb"));
        */
        $this->redirect();
    }
    public function my_dp()
    {
        $uinfo = $this->model->table("customer")->where("user_id = ".$this->user['id'])->find();
        $info = $this->model->table("dp")->where("user_id = ".$this->user['id'])->find();
        $this->assign("info",$info);
        $this->redirect();
    }
    //商品上下架
    public function set_online()
    {
        $id = Req::args("id");
        // if(is_array($id)){
        //     $id = implode(',', $id);
        // }
        $status = Filter::int(Req::args('status'));
        // if($status!=0 && $status!=1) $status = 0;
        $model = new Model('goods');
        $on_isok=$model->fields("is_online,id")->where("id=".$id)->find()['is_online'];
        if ($on_isok<2) {
            $model->data(array('is_online'=>$status))->where("id = $id and seller_id=".$this->user['id'])->update();
        }
        $this->redirect("goods_list");
    }
    //删除商品
    function goods_del()
    {
        $id = Req::args("id");
        $uid = Req::args("c");
        if ($uid==$this->user['id']) {
            $model = new Model();
                $model->table("spec_attr")->where("goods_id = $id")->delete();
                $model->table("products")->where("goods_id = $id")->delete();
                $model->table("goods")->where("id = $id ")->delete();
        }
        $this->redirect("goods_list");
    }

    //申请店铺
    public function dp_add()
    {
        $id = $this->user['id'];
        $dplx=Filter::int(Req::args('lx'));
        $dp_money=Zyk_tj::zyk_info('qylx',$dplx,'money');
        $u_balance=Common::getC($id)['balance'];
        if ($u_balance<$dp_money) {
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","账户余额不足，无法申请商家，请先充值账户！")));
        }else{
            $dp_data = array(
                'user_id'=>$id,
                'dp_name'=>Filter::txt(Req::args('dp_name')),
                'dp_dm'=>Filter::txt(Req::args('dp_dm')),
                'category_id'=>Filter::int(Req::args('category_id')),
                //'dp_zizhi'=>Filter::txt(Req::args('dp_zizhi')),
                'dp_logo'=>Filter::txt(Req::args('dp_logo')),
                'dp_tel'=>Filter::txt(Req::args('dp_tel')),
                'province'=>Filter::int(Req::args('province')),
                'city'=>Filter::int(Req::args('city')),
                'county'=>Filter::int(Req::args('county')),
                'dp_lx'=>$dplx,
                'sq_time'=>date('Y-m-d H:i:s'),
                'is_ok'=>1,
                'dp_addr'=>Filter::txt(Req::args('addr'))
                );
                
            $sq_data = array(
                'user_id'=>$id,
                'sq_lx'=>2,
                'sq_money'=>$dp_money,
                'sq_time'=>date('Y-m-d H:i:s')
                );
            $this->model->table("sq_list")->data($sq_data)->insert();
            $this->model->table("dp")->data($dp_data)->insert();
            $this->model->table("customer")->data(array('balance'=>"`balance`-$dp_money"))->where("user_id=".$id)->update();
            $this->redirect("sq_ckordp",false,array('msg'=>array("success","申请成功，等待审核！")));
        }
        
    }
    //修改店铺
    public function dp_mod()
    {
        $id = $this->user['id'];
        // $dplx=Filter::int(Req::args('lx'));
        // $dp_money=Zyk_tj::zyk_info('qylx',$dplx,'money');
        // $u_balance=Common::getC($id)['balance'];
        // if ($u_balance<$dp_money) {
        //     $this->redirect("sq_ckordp",false,array('msg'=>array("error","账户余额不足，无法申请商家，请先充值账户！")));
        // }else{
            $dp_data = array(
                'user_id'=>$id,
                // 'dp_name'=>Filter::txt(Req::args('dp_name')),
                // 'dp_dm'=>Filter::txt(Req::args('dp_dm')),
                'category_id'=>Filter::int(Req::args('category_id')),
                'dp_content'=>Filter::text(Req::args('dp_content')),
                'dp_logo'=>Filter::txt(Req::args('dp_logo')),
                'dp_tel'=>Filter::txt(Req::args('dp_tel')),
                'province'=>Filter::int(Req::args('province')),
                'city'=>Filter::int(Req::args('city')),
                'county'=>Filter::int(Req::args('county')),
                // 'dp_lx'=>$dplx,
                // 'sq_time'=>date('Y-m-d H:i:s'),
                // 'is_ok'=>1,
                'dp_addr'=>Filter::txt(Req::args('addr'))
                );
            // $sq_data = array(
            //     'user_id'=>$id,
            //     'sq_lx'=>2,
            //     'sq_money'=>$dp_money,
            //     'sq_time'=>date('Y-m-d H:i:s')
            //     );
            // $this->model->table("sq_list")->data($sq_data)->insert();
            $this->model->table("dp")->data($dp_data)->where("user_id=".$id)->update();
            // $this->model->table("customer")->data(array('balance'=>"`balance`-$dp_money"))->where("user_id=".$id)->update();
            $this->redirect("my_dp",false,array('msg'=>array("success","修改成功！")));
        // }
        
    }
    //开通创客
    public function sq_ck()
    {
        $id = $this->user['id'];
        $ck_money=Common::getConfigJjsetValue("jjset_ck_chongzhi");
        $u_balance=Common::getC($id)['balance'];
        $ye=$u_balance-$ck_money;
        if ($ye<0) {
            $info = array('msg'=>'账户余额不足，无法申请创客，请先充值账户！');
        }else{
            //赠送各种币
            $zsb = array(
                'ck_ok'=>1,
                'balance'=>$ye,
                'xxb'=>Common::getConfigJjsetValue("jjset_xxb"),
                'xyb'=>Common::getConfigJjsetValue("jjset_xyb"),
                'gwb'=>Common::getConfigJjsetValue("jjset_gwb")
            );
            $this->model->table("user")->data(array('u_lx'=>1))->where("id=".$id)->update();
            $this->model->table("customer")->data($zsb)->where("user_id=".$id)->update();
            //Jjjs::tjj_ckordp($id,1);
            $info = array('status'=>'success');
        }
        echo JSON::encode($info);
    }
    
    
    /**
     * 保存用户申请信息
     */
    static function save_sq_info($user_id, $sq_lx)
    {
        $arr['user_id'] = $user_id;
        $arr['sq_lx']   = $sq_lx;
        $arr['sq_time'] = date('Y-m-d H:i:s');
        $model = new Model();
        $result = $model->table("sq_list")->data($arr)->insert();
        return $result;
    }
    
    
    
    //申请代理
    //必须是合格会员
    public function agent_add()
    {
        $id       = $this->user['id'];
        $sq_lx    = intval( Filter::int(Req::args('lx')) );
        $user_obj = Common::get_user_obj($id);
        $u_lx     = intval($user_obj['u_lx']);
        //直推人数
        $u_tjrs   = $user_obj['u_tjrs'];
        $tuan_yj  = $user_obj['tuan_yj'];
        
        $glj1 = Common::getConfigJjsetValue("jjset_glj1");//服务中心的直推人数
        $glj2 = Common::getConfigJjsetValue("jjset_glj2");//服务中心的团队业绩
        $glj3 = Common::getConfigJjsetValue("jjset_glj3");//分公司的直推人数
        
        $result = false;
        
        $model = new Model();
        
        //判断之前的审核是否通过
        $sq_count = $model->table("sq_list")->where("user_id=$id and is_ok=0")->count();
        
        if($sq_count > 0)
        {
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","您之前提交的申请正在审核中，请不要重复提交！")));
            die;
        }
        
        if($u_lx === 0)
        {
            //如果用户不是合格的会员，则无法提出申请
            if(intval($user_obj['is_hg']) === 0)
            {
                //不满足条件
                $this->redirect("sq_ckordp",false,array('msg'=>array("error","您的条件不满足，暂时无法申请！")));
                die;
            }
            
            if($sq_lx === 1)//申请的是服务中心
            {
                if($u_tjrs>=$glj1 && $tuan_yj>=$glj2)
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
                else
                {
                    //不满足条件
                    $this->redirect("sq_ckordp",false,array('msg'=>array("error","您的条件不满足，暂时无法申请！")));
                    die;
                }
            }
            elseif($sq_lx === 2)//申请的是分公司
            {
                if($tuan_yj >= $glj3)
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
                else
                {
                    //不满足条件
                    $this->redirect("sq_ckordp",false,array('msg'=>array("error","您的条件不满足，暂时无法申请！")));
                    die;
                }
            }
        }
        elseif($u_lx === 1)
        {
            if($sq_lx === 1)
            {
                $this->redirect("sq_ckordp",false,array('msg'=>array("error","您当前的身份已经是服务中心，请不要重复操作！")));
                die;
            }
            elseif($sq_lx === 2)
            {
                if($tuan_yj< $glj3)
                {
                    //不满足条件
                    $this->redirect("sq_ckordp",false,array('msg'=>array("error","您的条件不满足，暂时无法申请！")));
                    die;
                }
                else 
                {
                    $result = self::save_sq_info($id, $sq_lx);
                }
            }
        }
        elseif($u_lx === 2)
        {
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","您当前已经是分公司了，请不要重复操作！")));
            die;
        }
        
        if($result)
        {
            $this->redirect("sq_ckordp",false,array('msg'=>array("success","申请成功，等待审核！")));
        }
        else
        {
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","操作失败！")));
        }
        
        
        
        
        /*
        $id    = $this->user['id'];
        $dllx  = Filter::int(Req::args('lx'));
        $sheng = Filter::int(Req::args('province'));
        $shi   = Filter::int(Req::args('city'));
        $xian  = Filter::int(Req::args('county'));
        $dlqy  = $sheng.$shi.$xian;
        $dl_money  = Zyk_tj::zyk_info('agentlx',$dllx,'money');
        $u_balance = Common::getC($id)['balance'];
        $qynum     = Zyk_tj::count('agent',"dl_qy='$dlqy'");
        // $this->redirect("sq_ckordp",false,array('msg'=>array("error",intval($shi))));
        // exit;
        if ($dllx==1 && intval($shi)>0) {
            $isok=1;
            $mss='申请代理类型为省代，请不要选市区';
        }elseif ($dllx==2 && intval($shi)==0){
            $isok=1;
            $mss='申请代理类型为市代，请选择市区';
        }elseif ($dllx==3 && intval($xian)==0){
            $isok=1;
            $mss='申请代理类型为县区代，请选择县区';
        }elseif ($dllx==2 && intval($xian)>0){
            $isok=1;
            $mss='申请代理类型为市代，请不要选择县区';
        }

        if ($u_balance<$dl_money) {
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","账户余额不足，无法申请代理，请先充值账户！")));
        }elseif ($qynum>0){
            $this->redirect("sq_ckordp",false,array('msg'=>array("error","您申请的区域已有代理，请更换区域！")));
        }elseif ($isok==1){
            $this->redirect("sq_ckordp",false,array('msg'=>array("error",$mss)));
        }else{
            $dl_data = array(
                'user_id'=>$id,
                'dl_tel'=>Filter::txt(Req::args('dl_tel')),
                'province'=>$sheng,
                'city'=>$shi,
                'county'=>$xian,
                'dl_lx'=>$dllx,
                'sq_time'=>date('Y-m-d H:i:s'),
                'is_ok'=>1,
                'dl_qy'=>$dlqy
                );
            $sq_data = array(
                'user_id'=>$id,
                'sq_lx'=>3,
                'sq_money'=>$dl_money,
                'sq_time'=>date('Y-m-d H:i:s')
                );
            $this->model->table("sq_list")->data($sq_data)->insert();
            $this->model->table("agent")->data($dl_data)->insert();
            $this->model->table("customer")->data(array('balance'=>"`balance`-$dl_money"))->where("user_id=".$id)->update();
            $this->redirect("sq_ckordp",false,array('msg'=>array("success","申请成功，等待审核！")));
        }
        */
        
    }

    public function info_save()
    {
        //$rules = array('real_name:required:真实姓名不能为空!','sex:int:性别必需选择！','birthday:date:生日日期格式不正确！','province:[1-9]\d*:选择地区必需完成','city:[1-9]\d*:选择地区必需完成','county:[1-9]\d*:选择地区必需完成');
        $rules = array('real_name:required:真实姓名不能为空!');
        $info = Validator::check($rules);
        if(is_array($info)){
            $this->redirect("info",false,array('msg'=>array("info",$info['msg'])));
        }else{
            $data = array(
                    // 'name'=>Filter::txt(Req::args('name')),
                    'real_name'=>Filter::text(Req::args('real_name')),
                    'sex'=>Filter::int(Req::args('sex')),
                    'birthday'=>Filter::sql(Req::args('birthday')),

                    'mobile'=>Filter::sql(Req::args('mobile')),
                    'province'=>Filter::int(Req::args('province')),
                    'city'=>Filter::int(Req::args('city')),
                    'county'=>Filter::int(Req::args('county')),
                    'addr'=>Filter::text(Req::args('addr')),
                    'bank'=>Filter::text(Req::args('bank')),
                    'bank_kh'=>Filter::text(Req::args('bank_kh')),
                );


            // if($this->user['mobile'] == ''){
            //     $mobile = Filter::int(Req::args('mobile'));
            //     $obj = $this->model->table("customer")->where("mobile='$mobile'")->find();
            //     $data['mobile'] = $mobile;
            //     if($obj){
            //         $this->redirect("info",false,array('msg'=>array("info",'此手机号已经存在！')));
            //         exit;
            //     }
            // }
            // if($this->user['email'] == $this->user['mobile'].'@no.com'){
            //     $email = Req::args('email');
            //     if(Validator::email($email)){
            //         $userData['email'] = $email;
            //         $obj = $this->model->table("user")->where("email='$email'")->find();
            //         if($obj){
            //             $this->redirect("info",false,array('msg'=>array("info",'此邮箱号已存在')));
            //             exit;
            //         }
            //     }
            // }

            // $userData['name'] = Filter::sql(Req::args("name"));
            $id = $this->user['id'];
            $this->model->table("user")->data($userData)->where("id=$id")->update();

            $this->model->table("customer")->data($data)->where("user_id=$id")->update();
            $obj = $this->model->table("user as us")->join("left join customer as cu on us.id = cu.user_id")->fields("us.*,cu.group_id,cu.login_time,cu.mobile")->where("us.id=$id")->find();
                        $this->safebox->set('user',$obj,$this->cookie_time);
            $this->redirect("info",false,array('msg'=>array("success","保存成功！")));
        }
    }
    public function attention()
    {
        $page = Filter::int(Req::args('p'));
        $attention = $this->model->table("attention as at")->fields("at.*,go.name,go.store_nums,go.img,go.sell_price,go.id as gid")->join("left join goods as go on at.goods_id = go.id")->where("at.user_id = ".$this->user['id'])->findPage($page);
        $this->assign("attention",$attention);
        $this->redirect();
    }
    public function attention_del()
    {
        $id = Filter::int(Req::args("id"));
        if(is_array($id)){
            $ids = implode(",", $id);
        }else{
            $ids = $id;
        }
        $this->model->table("attention")->where("id in($ids) and user_id=".$this->user['id'])->delete();
        $this->redirect("attention");
    }
    public function order_detail()
    {
        $id = Filter::int(Req::args("id"));
        $order = $this->model->table("order as od")->fields("od.*,pa.pay_name")->join("left join payment as pa on od.payment = pa.id")->where("od.id = $id and od.user_id=".$this->user['id'])->find();
        if($order){
            $invoice = $this->model->table("doc_invoice as di")->fields("di.*,ec.code as ec_code,ec.name as ec_name,ec.alias as ec_alias")->join("left join express_company as ec on di.express_company_id = ec.id")->where("di.order_id=".$id)->find();
            $order_goods = $this->model->table("order_goods as og ")->join("left join goods as go on og.goods_id = go.id left join products as pr on og.product_id = pr.id")->where("og.order_id=".$id)->findAll();
            $area_ids = $order['province'].','.$order['city'].','.$order['county'];
            if($area_ids!='')$areas = $this->model->table("area")->where("id in ($area_ids)")->findAll();
            $parse_area = array();
            foreach ($areas as $area) {
                $parse_area[$area['id']] = $area['name'];
            }
            $this->assign("parse_area",$parse_area);
            $this->assign("order_goods",$order_goods);
            $this->assign("invoice",$invoice);
            $this->assign("order",$order);
            $this->redirect();
        }else{
            Tiny::Msg($this, 404);
        }
    }
    //店铺订单查看
    public function dp_order_detail()
    {
        $id = Filter::int(Req::args("id"));
        $order = $this->model->table("order as od")->fields("od.*,pa.pay_name")->join("left join payment as pa on od.payment = pa.id")->where("od.id = $id")->find();
        if($order){
            $invoice = $this->model->table("doc_invoice as di")->fields("di.*,ec.code as ec_code,ec.name as ec_name,ec.alias as ec_alias")->join("left join express_company as ec on di.express_company_id = ec.id")->where("di.order_id=".$id)->find();
            $order_goods = $this->model->table("order_goods as og ")->join("left join goods as go on og.goods_id = go.id left join products as pr on og.product_id = pr.id")->where("og.order_id=".$id)->findAll();
            $area_ids = $order['province'].','.$order['city'].','.$order['county'];
            if($area_ids!='')$areas = $this->model->table("area")->where("id in ($area_ids)")->findAll();
            $parse_area = array();
            foreach ($areas as $area) {
                $parse_area[$area['id']] = $area['name'];
            }
            $this->assign("parse_area",$parse_area);
            $this->assign("order_goods",$order_goods);
            $this->assign("invoice",$invoice);
            $this->assign("order",$order);
            $this->redirect();
        }else{
            Tiny::Msg($this, 404);
        }
    }
    //订单签收
    public function order_sign()
    {
        $id = Filter::int(Req::args("id"));
        $info = array('status'=>'fail');
        $result = $this->model->table('order')->where("id=$id and user_id=".$this->user['id']." and status=3 and pay_status=1 and delivery_status=1")->data(array('delivery_status'=>2,'status'=>4,'completion_time'=>date('Y-m-d H:i:s')))->update();
        if($result){
            
            //提取购买商品信息
            $products = $this->model->table('order as od')->join('left join order_goods as og on od.id=og.order_id')->where('od.id='.$id)->findAll();
            foreach ($products as $product) {
                $data = array('goods_id'=>$product['goods_id'],'user_id'=>$this->user['id'],'order_no'=>$product['order_no'],'buy_time'=>$product['create_time']);
                $this->model->table('review')->data($data)->insert();
                $je=$product['goods_price']*$product['goods_nums'];
                //Jjjs::tjj_buy($product['dp_id'],$je);//商家推荐人提成结算
            }
            //计算奖金
            $orderss = $this->model->table("order")->where("id=".$id)->find();
            Pointlog::write($orderss['user_id'], $orderss['point'], '购买商品，订单：'.$orderss['order_no'].' 得'.$orderss['point'].'积分',$orderss['order_amount']);
            $info = array('status'=>'success');
        }
        echo JSON::encode($info);
    }
    public function address()
    {
        $model = new Model("address");
        $address = $model->where("user_id=".$this->user['id'])->order("id desc")->findAll();
        $area_ids = array();
        foreach ($address as $addr) {
            $area_ids[$addr['province']] = $addr['province'];
            $area_ids[$addr['city']] = $addr['city'];
            $area_ids[$addr['county']] = $addr['county'];
        }
        $area_ids = implode(',', $area_ids);
        $areas = array();
        if($area_ids!='')$areas = $model->table("area")->where("id in ($area_ids)")->findAll();
        $parse_area = array();
        foreach ($areas as $area) {
            $parse_area[$area['id']] = $area['name'];
        }
        $this->assign("address",$address);
        $this->assign("parse_area",$parse_area);
        $this->redirect();
    }
    public function address_del()
    {
        $id = Filter::int(Req::args("id"));
        $this->model->table("address")->where("id=$id and user_id=".$this->user['id'])->delete();
        $this->redirect("address");
    }
    public function index()
    {
        $id = $this->user['id'];

        //计算团队业绩
        Common::jisuan_tuan_yj($id);

        $customer = $this->model->table("customer as cu")->fields("cu.*,gr.*")->join("left join user as gr on cu.user_id = gr.id")->where("cu.user_id = $id")->find();
        $orders = $this->model->table("order")->where("user_id = $id")->findAll();
        $order = array('amount'=>0,'pending'=>0);
        foreach ($orders as $obj) {
            if($obj['status']==4)$order['amount'] += $obj['order_amount'];
            else if($obj['status']<3)$order['pending']++;
        }
        $comment = $this->model->table("review")->fields("count(*) as num")->where("user_id = $id and status=0")->find();
        $this->assign("comment",$comment);
        $this->assign("order",$order);
        $this->assign("customer",$customer);
        $this->redirect();
    }

    protected function order_status($item)
    {
        $status = $item['status'];
        $pay_status = $item['pay_status'];
        $delivery_status = $item['delivery_status'];
        $str = '';
        switch ($status) {
            case '1':
                $str = '<span class="text-danger">等待付款</span> <a href="'.Url::urlFormat("/simple/order_status/order_id/$item[id]").'" class="btn btn-main btn-mini">付款</a>';
                break;
            case '2':
                if($pay_status ==1) $str = '<span class="text-warning">等待审核</span>';
                if($pay_status==2)$str = '<span class="text-success">退款中</span>';
                else {
                    $payment_info = Common::getPaymentInfo($item['payment']);
                    if($payment_info['class_name']=='received')
                        $str = '<span class="text-warning">等待审核 <a href="'.Url::urlFormat("/simple/order_status/order_id/$item[id]").'" class="btn btn-main btn-mini">另选支付</a></span>';
                    else
                    $str = '<span class="text-danger">等待付款 <a href="'.Url::urlFormat("/simple/order_status/order_id/$item[id]").'" class="btn btn-main btn-mini">付款</a></span>';
                }
                break;
            case '3':
                if($delivery_status == 0) $str = '<span class="text-info">等待发货</span>';
                else if($delivery_status == 1) $str = '<span class="text-info">已发货</span> <a href="javascript:;" class="btn btn-main btn-mini" onclick="order_sign('.$item['id'].')">已收货</a>';
                if($pay_status==2)$str = '<span class="text-success">退款中</span>';
                if($pay_status==3)$str = '<span class="text-success">已退款</span>';
                break;
            case '4':
                $str = '<span class="text-success"><b>已完成</b></span>';
                if($pay_status==3)$str = '<span class="text-success">已退款</span>';
                break;
            case '5':
                $str = '<span class="text-gray"><s>已取消</s></span>';
                break;
            case '6':
                $str = '<span class="text-gray"><s>已作废</s></span>';
                break;
            default:
                # code...
                break;
        }
        return $str;
    }

    //检测用户是否在线
    private function checkOnline()
    {
        if(isset($this->user)&& $this->user['name']!=null)
            return true;
        else return false;
    }

    //上传图片
    function upload_image()
    {
        $upfile_path = Tiny::getPath("uploads");
        $upfile_url = Tiny::getPath("uploads_url");
        $upfile = new UploadFile('imgFile',$upfile_path,'10m');
        $upfile->save();
        $info = $upfile->getInfo();
        $result = array();
        if($info[0]['status']==1){
            $result = array('error'=>0,'url'=>$upfile_url.$info[0]['path']);
        }
        else{
            $result = array('error'=>1,'message'=>$info[0]['msg']);
        }
        echo JSON::encode($result);
    }

    //上传头像
    public function upload_head()
    {
        $upfile_path = Tiny::getPath("uploads")."/head/";
        $upfile_url = preg_replace("|".APP_URL."|",'',Tiny::getPath("uploads_url")."head/",1);
        //$upfile_url = strtr(Tiny::getPath("uploads_url")."head/",APP_URL,'');
        $upfile = new UploadFile('imgFile',$upfile_path,'500k','','hash',$this->user['id']);
        $upfile->save();
        $info = $upfile->getInfo();
        $result = array();
        if($info[0]['status']==1){
            $result = array('error'=>0,'url'=>$upfile_url.$info[0]['path']);
            $image_url = $upfile_url.$info[0]['path'];
            $image = new Image();
            $image->suffix = '';
            $image->thumb(APP_ROOT.$image_url,100,100);
            $model = new Model('user');
            $model->data(array('head_pic'=>$image_url))->where("id=".$this->user['id'])->update();

            $safebox =  Safebox::getInstance();
            $user = $this->user;
            $user['head_pic'] = $image_url;
            $safebox->set('user',$user);
        }
        else{
            $result = array('error'=>1,'message'=>$info[0]['msg']);
        }
        echo JSON::encode($result);
    }

    //图库文件
    function photoshop()
    {
        $this->layout = '';
        $this->redirect();
    }
    //图库图片上传
    function photoshop_upload()
    {
        $file = $_FILES['upfile'];
        if($file['error']==4){
            $msg = array('error','请选择文件后再上传！');
            $this->redirect("photoshop",true,array('msg'=>$msg));
        }
        else if($file['error']==1){
            $msg = array('error','文件超出了php.ini文件指定大小！');
            $this->redirect("photoshop",true,array('msg'=>$msg));
        }
        else if($file['size']>0){
            $key = md5_file($file['tmp_name']);
            $gallery = new Model('gallery');
            $img = $gallery->where("`key`='".$key."'")->find();
            echo JS::import('dialog?skin=tinysimple');
            echo JS::import('dialogtools');
            if(!$img){
                $upfile_path = Tiny::getPath("uploads");
                $upfile_url = preg_replace("|^".APP_URL."|",'',Tiny::getPath("uploads_url"));
                $upfile = new UploadFile('upfile',$upfile_path,'10m');
                $upfile->save();
                $info = $upfile->getInfo();
                $result = array();
                if($info[0]['status']==1){
                    $url = $upfile_url.$info[0]['path'];
                    $key = md5_file($upfile_path.$info[0]['path']);
                    $type = Req::args("type")==null?0:intval(Req::args('type'));
                    $gallery->data(array('key'=>$key,'type'=>$type,'img'=>$url))->save();
                    echo("<script>art.dialog.opener.setImg('$url');</script>");
                }
                else{
                    $msg = array('error',$info[0]['msg']);
                    $this->msg = $msg;
                    $this->redirect("photoshop",false);
                }
            }else{
                $url = $img['img'];
                echo("<script>art.dialog.opener.setImg('$url');</script>");
            }
        }
        exit;
    }

    //商品处理
    function goods_save(){
    	$seller_id = Req::args('seller_id');
        $spec_items = Req::args('spec_items');
        $spec_item = Req::args('spec_item');
        $items = explode(",", $spec_items);
        $values_array = array();
        //货品中的一些变量
        $pro_no = Req::args("pro_no");
        $store_nums = Req::args("store_nums");
        $warning_line = Req::args("warning_line");
        $weight = Req::args("weight");
        $sell_price = Req::args("sell_price");
        $k_point = Req::args("k_point");
        $market_price = Req::args("market_price");
        $cost_price = Req::args("cost_price");

        //values的笛卡尔积
        $values_dcr = array();
        $specs_new = array();
        if(is_array($spec_item)){
            foreach ($spec_item as $item) {
                $values = explode(",", $item);

                foreach ($values as $value) {
                    $value_items = explode(":", $value);
                    $values_array[$value_items[0]]=$value_items;
                }
            }
            $value_ids = implode(",",array_keys($values_array));
            $values_model = new Model('spec_value');
            $spec_model = new Model('goods_spec');
            $specs = $spec_model->where("id in ({$spec_items})")->findAll();
            $values = $values_model->where("id in ({$value_ids})")->order('sort')->findAll();
            $values_new = array();
            foreach ($values as $k => $row) {
                $current = $values_array[$row['id']];
                if($current[1]!=$current[2]) $row['name'] = $current[2];
                if($current[3]!='') $row['img'] = $current[3];
                $values_new[$row['spec_id']][$row['id']] = $row;
            }

            foreach ($specs as $key => $value) {
                $value['value'] = isset($values_new[$value['id']])?$values_new[$value['id']]:null;
                $specs_new[$value['id']] = $value;
            }

            foreach ($spec_item as $item) {
                $values = explode(",", $item);
                $key_code = ';';
                foreach ($values as $k => $value) {
                    $value_items = explode(":", $value);
                    $key = $items[$k];
                    $tem[$key] = $specs_new[$key];
                    $tem[$key]['value'] = $values_array[$value_items[0]];
                    $key_code .= $key.':'.$values_array[$value_items[0]][0].';';
                }
                $values_dcr[$key_code] = $tem;
            }
        }

        //商品处理
        $goods = new Model('goods');
        Req::args('specs',serialize($specs_new));
        $attrs = is_array(Req::args("attr"))?Req::args("attr"):array();
        $imgs = is_array(Req::args("imgs"))?Req::args("imgs"):array();
        Req::args('attrs',serialize($attrs));
        Req::args('imgs',serialize($imgs));
        Req::args('up_time',date("Y-m-d H:i:s"));

        $id = intval(Req::args("id"));
        $gdata = Req::args();
        $gdata['name'] = Filter::sql($gdata['name']);
        if(is_array($gdata['pro_no'])) $gdata['pro_no'] = $gdata['pro_no'][0];
        if($id==0){
            $gdata['create_time'] = date("Y-m-d H:i:s");
            $goods_id = $goods->data($gdata)->save();
            // Log::op($this->manager['id'],"添加商品","管理员[".$this->manager['name']."]:添加了商品 ".Req::args('name'));
        }else{
            $goods_id = $id;
            $goods->data($gdata)->where("id=".$id)->update();
            // Log::op($this->manager['id'],"修改商品","管理员[".$this->manager['name']."]:修改了商品 ".Req::args('name'));
        }
        //货品添加处理
        $g_store_nums = $g_warning_line = $g_weight = $g_sell_price = $g_market_price = $g_k_point = $g_cost_price = 0;
        $products = new Model("products");
        $k = 0;
        foreach ($values_dcr as $key => $value) {
            $result = $products->where("goods_id = ".$goods_id." and specs_key = '$key'")->find();

            $data = array('goods_id' =>$goods_id,'pro_no'=>$pro_no[$k],'store_nums'=>$store_nums[$k],'warning_line'=>$warning_line[$k],'weight'=>$weight[$k],'sell_price'=>$sell_price[$k],'k_point'=>$k_point[$k],'market_price'=>$market_price[$k],'cost_price'=>$cost_price[$k],'specs_key'=>$key,'spec'=>serialize($value));
            $g_store_nums += $data['store_nums'];
            if($g_warning_line==0) $g_warning_line = $data['warning_line'];
            else if($g_warning_line>$data['warning_line']) $g_warning_line = $data['warning_line'];
            if($g_weight==0) $g_weight = $data['weight'];
            else if($g_weight<$data['weight']) $g_weight = $data['weight'];
            if($g_sell_price==0) $g_sell_price = $data['sell_price'];
            else if($g_sell_price>$data['sell_price']) $g_sell_price = $data['sell_price'];
            if($g_k_point==0) $g_k_point = $data['k_point'];
            else if($g_k_point<$data['k_point']) $g_k_point = $data['k_point'];
            if($g_market_price==0) $g_market_price = $data['market_price'];
            else if($g_market_price<$data['market_price']) $g_market_price = $data['market_price'];
            if($g_cost_price==0) $g_cost_price = $data['cost_price'];
            else if($g_cost_price<$data['cost_price']) $g_cost_price = $data['cost_price'];

            if(!$result){
                $products->data($data)->insert();
            }else{
                $products->data($data)->where("goods_id=".$goods_id." and specs_key='$key'")->update();
            }
            $k++;
        }
        //如果没有规格
        if($k==0){
            $g_store_nums = $store_nums;
            $g_warning_line = $warning_line;
            $g_weight = $weight;
            $g_sell_price = $sell_price;
            $g_k_point = $k_point;
           $g_market_price = $market_price;
            $g_cost_price = $cost_price;
            $data = array('goods_id' =>$goods_id,'pro_no'=>$pro_no,'store_nums'=>$store_nums,'warning_line'=>$warning_line,'weight'=>$weight,'sell_price'=>$sell_price,'k_point'=>$k_point,'market_price'=>$market_price,'cost_price'=>$cost_price,'specs_key'=>'','spec'=>serialize(array()));
            $result = $products->where("goods_id = ".$goods_id)->find();
            if(!$result){
                $data['u_dp_id'] = $seller_id;//自己加的
            	$data['seller_id'] = $seller_id;//自己加的
                $products->data($data)->insert();
            }else{
                $products->data($data)->where("goods_id=".$goods_id)->update();
            }
        }
        //更新商品相关货品的部分信息
        $goods->data(array('store_nums'=>$g_store_nums,'warning_line'=>$g_warning_line,'weight'=>$g_weight,'sell_price'=>$g_sell_price,'k_point'=>$g_k_point,'market_price'=>$g_market_price,'cost_price'=>$g_cost_price))->where("id=".$goods_id)->update();

        $keys = array_keys($values_dcr);
        $keys = implode("','", $keys);
        //清理多余的货品
        $products->where("goods_id=".$goods_id." and specs_key not in('$keys')")->delete();

        //规格与属性表添加部分
        $spec_attr = new Model("spec_attr");
        //处理属性部分

        $value_str = '';
        if($attrs){
            foreach ($attrs as $key => $attr) {
                if(is_numeric($attr)) $value_str .= "($goods_id,$key,$attr),";
            }
        }
        foreach ($specs_new as $key => $spec) {
            if(isset($spec['value']))foreach($spec['value'] as $k => $v)$value_str .= "($goods_id,$key,$k),";
        }
        $value_str = rtrim($value_str,',');
        //更新商品键值对表
        $spec_attr->where("goods_id = ".$goods_id)->delete();
        $dbinfo = DBFactory::getDbInfo();
        $spec_attr->query("insert into {$dbinfo['tablePre']}spec_attr values $value_str");
        $this->redirect("goods_list");
    }
    
    
    function show_spec_select(){
        $this->layout = '';
        $this->redirect();
    }

    public function goods_edit()
    {
        $id=Req::args("id");
        $model = new Model("goods");
        if(empty($id))
        {
            $this->assign("title","添加商品：");
        }
        else
        {
            $this->assign("title","编辑商品：");
            $goods_obj=$model->where("id=".$id)->find();
            
            $this->assign("goods_obj", $goods_obj);
            $this->assign("id", $id);
        }
        $this->redirect();
    }
    
    
    function sell_order_list()
    {
    	$this->redirect();
    }
    
    
    
	//pc端商家订单发货
    public function order_send()
    {
    	//Req::post("admin",$this->manager['name']);
		//Req::post("create_time",date('Y-m-d H:i:s'));
		//Req::post("invoice_no",date('YmdHis').rand(100,999));
		//$order_id = Filter::int(Req::args("order_id"));
		//$express_no = Filter::str(Req::args("express_no"));
		//$express_company_id = Filter::int(Req::args('express_company_id'));
		$model = new Model("doc_invoice");//发货表
		
		$data['admin'] = $this->user['name'];//发货人姓名
		$data['create_time'] = date('Y-m-d H:i:s');//发货时间
		$data['invoice_no'] = date('YmdHis').rand(100,999);//发货单号
		$order_id = Req::args("order_id");//订单id
		$data['order_id'] = $order_id;
		
		$orderObj = $model->table("order")->where("id=".$order_id)->find();
		
		$data['order_no'] = $orderObj['order_no'];
		$data['accept_name'] = $orderObj['accept_name'];
		$data['province'] = $orderObj['province'];
		$data['city'] = $orderObj['city'];
		$data['county'] = $orderObj['county'];
		$data['zip'] = $orderObj['zip'];
		$data['addr'] = $orderObj['addr'];
		$data['phone'] = $orderObj['phone']?$orderObj['phone']:'';
		$data['mobile'] = $orderObj['mobile'];
		
		$express_no = Req::args("express_no");//物流单号
		$data['express_no'] = $express_no;
		$express_company_id = Req::args("express_company_id");//物流公司id
		$data['express_company_id'] = $express_company_id;
		
		$model->table("doc_invoice")->data($data)->insert();

		//$delivery_status = Req::args("delivery_status");
//		if($delivery_status==3){
//			$model->where("order_id=$order_id")->insert();
//		}
//		else{
//			$obj = $model->where("order_id=$order_id")->find();
//			if($obj){
//				$model->where("order_id=$order_id")->update();
//			}else{
//				$model->where("order_id=$order_id")->insert();
//			}
//		}
		//同步发货信息
		$order_info = $model->table("order")->where("id=$order_id")->find();
		if($order_info){
			if($order_info['trading_info']!=''){
				$payment_id = $order_info['payment'];
				$payment = new Payment($payment_id);
				$payment_plugin = $payment->getPaymentPlugin();
				$express_company = $model->table('express_company')->where('id='.$express_company_id)->find();
				if($express_company) $express = $express_company['name'];
				else $express = $express_company_id;
				//处理同步发货
				$delivery = $payment_plugin->afterAsync();
				if($delivery!=null && method_exists($delivery, "send")) $delivery->send($order_info['trading_info'],$express,'express_no');
			}
		}
		$model->table("order")->where("id=$order_id")->data(array('delivery_status'=>1,'send_time'=>date('Y-m-d H:i:s')))->update();
		$url=Url::createUrl("/ucenter/sell_order_list");
		echo "<script>alert('操作成功！');location.href='{$url}';</script>";
    }
    
    
    
    
    /**
     * 在交易大厅每天卖出可用消费积分
     */
    public function sell_ok_xfjf()
    {
        $user_id = $this->user['id'];
        //卖出数量是否为100的倍数
        //卖出单价是否》=0.9
        //交易密码是否正确
        //账户余额是否不足
        //扣除账户金额
        //保存相关数据到交易表中
        //返回结果
        $quantity = intval(Filter::int(Req::args("quantity")));
        $price    = floatval( Filter::float(Req::args('price')));
        $pass2    = strval(Filter::text(Req::args('pass2')));
        $desc     = strval(Filter::text(Req::args('desc')));
        
        if($quantity >= 100 && $quantity % 100 ==0)
        {
        }
        else
        {
            Common::return_info_msg("fail", "卖出数量必须为100的倍数");
            die;
        }
        
        //从配置文件中找到可用积分的最低单价
        $ok_xfjf_price1 = floatval( Common::getConfigJjsetValue("jjset_ok_xfjf_price1") );
        $ok_xfjf_price2 = floatval( Common::getConfigJjsetValue("jjset_ok_xfjf_price2") );
        if( $price < $ok_xfjf_price1  || $price > $ok_xfjf_price2)
        {
            Common::return_info_msg("fail", "卖出价格范围为$ok_xfjf_price1 - $ok_xfjf_price2");
            die;
        }
        
        if(!Common::check_pass2($user_id, $pass2))
        {
            Common::return_info_msg("fail", "您输入的交易密码不正确");
            die;
        }
        $model        = new Model();
        $customer_obj = $model->table("customer")->fields("ok_xfjf")->where("user_id=$user_id")->find();
        //可用积分账户余额
        $ok_xfjf = $customer_obj['ok_xfjf'];
        if($price * $quantity > $ok_xfjf)
        {
            Common::return_info_msg("fail", '可用积分余额不足');
            die;
        }
        $model->query("start transaction");
        $res1 = $model->table("customer")->data(['ok_xfjf'=>"`ok_xfjf`-$quantity"])->where("user_id=$user_id")->update();
        $data['user_id']       = $user_id;  //卖家用户id
        $data['price']         = $price;  //卖出单价
        $data['quantity']      = $quantity;//初始数量
        $data['last_quantity'] = $quantity;//剩余数量
        if(!empty($desc))
        {
            $data['desc']          = $desc;
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $res2 = $model->table("transaction_sell")->data($data)->insert();
        if($res1 && $res2)
        {
            $model->query("commit");
            Common::return_info_msg("success", '操作成功');
            die;
        }
        else
        {
            $model->query("rollback");
            Common::return_info_msg("fail", '操作失败');
            die;
        }
        
    }
    
    
    /**
     * 在交易大厅每天买入可用消费积分
     */
    public function buy_ok_xfjf()
    {
        if( !Common::is_not_allow_do_by_time())
        {
            Common::return_info_msg("fail", "此时不允许执行该操作");
            die;
        }
        
        //买方用户id
        $user_id = $this->user['id'];
        
        $sell_id = intval(Req::args("sell_id"));
        //购买的数量
        $quantity = intval(Filter::int(Req::args("quantity")));
        //$price    = floatval( Filter::float(Req::args('price')));
        //交易密码
        $pass2    = strval(Filter::text(Req::args('pass2')));
        
        /*
         * 二级密码是否正确
         * 买入数量是否超标
         * 账户余额是否不足
         * 买方用账户余额购买，购买成功后，
         *                           对于卖方来说，直接到账号账户余额(总价格扣除15%的反哺费，同时反哺费加入到每日消费总金额用于加权分红)
         *                           对于买方来说，直接到帐到通用积分账户,同时扣除买方的账户余额金额
         *                           扣除的反哺费保存到新增业绩表中
         * 保存购买记录到transaction_buy表
         * transaction_sell表的对应买家的last_quantity累减
         * 
         */
        
        $model = new Model();
        if(!Common::check_pass2($user_id, $pass2))
        {
            Common::return_info_msg("fail", "您输入的交易密码不正确");
            die;
        }
        
        $transaction_sell_obj = $model->table("transaction_sell")->where("id=$sell_id")->find();
        //剩余可购买数量
        $sell_last_quantity   = intval( $transaction_sell_obj['last_quantity'] );
        //单价
        $price                = floatval( $transaction_sell_obj['price'] );
        //卖方用户id
        $seller_id            = intval( $transaction_sell_obj['user_id'] );
        
        
        if($quantity > $sell_last_quantity)
        {
            Common::return_info_msg("fail", "最多可买".$sell_last_quantity);
            die;
        }
        
        if($quantity < 1)
        {
            Common::return_info_msg("fail", "买入数量至少为1");
            die;
        }
        //获得买方对象
        $customer_obj = $model->table("customer")->fields("balance")->where("user_id=$user_id")->find();
        
        //获得买方账户余额
        $balance = floatval( $customer_obj['balance'] );
        //购买需要支付的总金额
        $buy_dz_je = $quantity * $price;
        
        if($balance < $buy_dz_je)
        {
            Common::return_info_msg("fail", "账户余额不足");
            die;
        }
        
        $model->query("start transaction");
        
        //购买成功，买方通用积分累加,账户余额累减
        //比如用270块钱去买300个单价为0.9的通用积分,通用积分到帐的是买的数量,而扣除的是单价*数量，包括买家的到帐金额也是单价*数量
        $res1 = $model->table("customer")->data(['currency_point'=>"`currency_point`+$quantity",'balance'=>"`balance`-$buy_dz_je"])->where("user_id=$user_id")->update();
        
        //购买成功，卖方到帐到账户余额，实际到帐金额 = 总金额 - 反哺费
        $fbf_bili = Common::getConfigJjsetValue("jjset_fbf")/100;
        
        //反哺费
        $fbf_je = $buy_dz_je * $fbf_bili;
        
        //计算出对于卖家来说最终的到帐金额
        $sell_dz_je = $buy_dz_je * (1 - $fbf_bili);
        
        if($sell_dz_je > 0)
        {
            //卖家直接到帐到 账户余额
            $res2 = $model->table("customer")->data(['balance'=>"`balance`+$sell_dz_je"])->where("user_id=$seller_id")->update();
            
        }
        
        
        //保存交易记录
        $data['sell_id']     = $sell_id;
        $data['seller_id']   = $seller_id;
        $data['user_id']     = $user_id;
        $data['price']       = $price;
        $data['quantity']    = $quantity;
        $data['fbf_je']      = $fbf_je;
        //买家到帐的是数量
        $data['buy_dz_je']   = $quantity;
        $data['sell_dz_je']  = $sell_dz_je;
        $data['create_time'] = date('Y-m-d H:i:s');
        
        $res3 = $model->table("transaction_buy")->data( $data )->insert();
        
        if($quantity === intval($sell_last_quantity))
        {
            $da = ['last_quantity'=>"`last_quantity`-$quantity",'status'=>1];
        }
        else
        {
            $da = ['last_quantity'=>"`last_quantity`-$quantity"];
        }
        //transaction_sell表中剩余可购买数量累减
        $res4 = $model->table("transaction_sell")->data( $da )->where("id=$sell_id")->update();
        
        //奖扣除的反哺费保存到新增业绩表中
        $res5 = $model->table("every_day_xzyj")->data(['user_id'=>$seller_id,'xzyj'=>$fbf_je,'status'=>1,'no'=>$res3,'create_time'=>date('Y-m-d H:i:s')])->insert();
        
        if($res1 && $res2 && $res3 && $res4 && $res5)
        {
            $model->query("commit");
            Common::return_info_msg("success", '操作成功');
            die;
        }
        else 
        {
            $model->query("rollback");
            Common::return_info_msg("fail", '操作失败');
            die;
        }
    }
    
    
    
    /**
     * 个人交易  撤销操作
     */
    public function go_back_sell()
    {     
        /**
         * 1. 退还可用积分
         * 2. 删除transaction_sell表对应的记录
         */
        
        $id = intval( Req::args("id") );
        $model = new Model();
        $transaction_sell_obj = $model->table("transaction_sell")->where("id=$id")->find();
        if(!empty($transaction_sell_obj))
        {
            $model->query("start transaction");
            $total_je = $transaction_sell_obj['last_quantity'];
            $res1 = $model->table("customer")->data(['ok_xfjf'=>"`ok_xfjf`+$total_je"])->where("user_id=".$transaction_sell_obj['user_id'])->update();
            $res2 = $model->table("transaction_sell")->where("id=$id")->delete();
            if($res1 && $res2)
            {
                $model->query("commit");
                Common::return_info_msg("success", '操作成功');
                die;
            }
            else 
            {
                $model->query("rollback");
                Common::return_info_msg("fail", '操作失败');
                die;
            }
        }
        else
        {
            Common::return_info_msg("fail", '操作失败');
            die;
        }
    }
    
    
    public function reg_user()
    {
        //echo Url::getHost('http');
        
        //echo $tjr_href;die;
        $this->redirect();
    }
    
    
    
    
    public function reg_act()
    {
        if($this->getModule()->checkToken('reg'))
        {
            $number = Filter::sql(Req::args('number'));//图鉴编号
            $uname = Filter::sql(Req::post('uname'));//手机号码
            
            $passWord = Req::post('password');//登录密码
            $passwordtwo = Req::args('passwordtwo');//支付密码
            $validate_code = Req::args('validate_code');//短信验证码
    
            //判断短信验证码是否正确
            $model = new Model();
    
    
            //判断推荐编号是否存在
            //查询推荐编号的数量
            if(empty($number))
            {
                $tjr_id = 0;
            }
            else
            {
                $number = strval(trim($number));
                //推荐编码为手机号或者编码都行
                $tjr_obj = $model->query("select * from zyk_user where number='{$number}' or name='{$number}';");
                $tjr_obj = $tjr_obj[0];
                if(empty($tjr_obj))
                {
                    $info['msg'] = '您输入的推荐人编号不存在';
                    $this->redirect("reg_user",false,array('msg'=>array("info",$info['msg'])));
                    die;
                }
                else
                {
                    $tjr_id = intval($tjr_obj['id']);
                }
            }
            
            if(!Common::check_tjr_is_wan($tjr_id))
            {
                $info['msg'] = '您输入上级推荐人还未购物，暂时无法完成注册';
                $this->redirect("reg_user",false,array('msg'=>array("info",$info['msg'])));
                die;
            }
    
            //判断用户名(手机号码)是否存在
            $sql = "select * from zyk_user where name='{$uname}'";
            if(Common::check_is_exists_of_talbe($sql))
            {
                $info['msg'] = '您输入的手机号码已存在！';
                $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                die;
            }
    
            if(strlen($passWord)<6 || strlen($passwordtwo)<6)
            {
                $info['msg'] = '密码长度必需大于等于6位！';
                $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                die;
            }
    
            //判断短信验证码是否正确
            $sms_code_obj = $model->table("sms_code")->where("mobile='{$uname}' and sms_code='{$validate_code}' and sms_is_used=0")->find();
            if(empty($sms_code_obj))
            {               
                $info['msg'] = '手机短信验证码不正确！';
                $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                die;
            }
            else
            {
                if(strtotime($sms_code_obj['sms_close_time']) < time())
                {                  
                    
                    $info['msg'] = '验证码已过期，请重新获取！';
                    $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                    die;
                }
            }
    
            $model->query("start transaction");
    
            $validcode = CHash::random(8);
            $pass      = CHash::md5($passWord,$validcode);
    
            //向user表中插入数据
            $last_id    = $model->table('user')->data(array('name'=>$uname,'tjr_id'=>$tjr_id,'password'=>$pass,'passwordtwo'=>CHash::md5($passwordtwo),'pass1'=>$passWord,'pass2'=>$passwordtwo,'validcode'=>$validcode,'status'=>1))->insert();
    
            $new_number = Common::create_number($uname);
            //$new_number = substr($uname,-6);
    
            $result1    = $model->table("user")->data(['number'=>$new_number])->where("id=$last_id")->update();
             
            //推荐人直推人数加1
            if($tjr_id > 0)
            {
                $result2 = $model->table("user")->data(['u_tjrs'=>"`u_tjrs`+1"])->where("id=".$tjr_id)->update();
                if(!$result2)
                {
                    $model->query("rollback");
                    $info['msg'] = '注册失败，请重新操作！';
                    $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                    die;
                }
            }
            $now_date    = date('Y-m-d H:i:s',time());
    
            //$result3 = $model->table("customer")->data(array('user_id'=>$last_id,'reg_time'=>$now_date))->insert();
            $result3 = $model->query("insert into zyk_customer (user_id,reg_time)values( $last_id,'$now_date')");
    
            //修改短信验证码状态
            $result4 = $model->table("sms_code")->data(['sms_is_used'=>1])->where("id=".$sms_code_obj['id'])->update();
    
    
    
            //if($result1 && $result2 && $result3 && $result4)
            if($result1 && $result4)
            {
                $model->query("commit");
                if( $tjr_id > 0 )
                {
                    //添加子孙链
                    Common::addChildLink($last_id, $tjr_obj['id']);
                }
                
                //赠送推广额度
                Jjjs::reg_zs_extend_je($last_id);
                
                $info['msg'] = '注册成功！';
                $this->redirect("reg_user",false,array('msg'=>array("success",$info['msg'])));
                die;
                
            }
            else
            {
                $model->query("rollback");                
                $info['msg'] = '注册失败，请重新操作！';
                $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
                die;
            }
            //记录登录信息
            $obj = $model->table("user as us")->join("inner join customer as cu on us.id = cu.user_id")->fields("us.*,cu.login_time")->where("us.name='$uname'")->find();
            //$this->safebox->set('user',$obj,1800);
            $this->safebox->set('user',$obj);
    
    
            //$args = array("t_name"=>$t_name,'user_name'=>$uname);
            $args = array("t_name"=>$tjr_obj['name'],'user_name'=>$uname);
            $this->redirect("reg_result",true,$args);
        }
        else
        {
            $info['msg'] = '注册无效！';
            $this->redirect("reg_user",false,array('msg'=>array("fail",$info['msg'])));
            die;
        }
    }
    
    
    
    /**
     * 删除订单
     */
    public function del_order()
    {
        $order_id = intval(Req::args('order_id'));
        
        $model    = new Model();
    
        $model->query("start transaction");
    
        $order_obj = Common::get_order_obj_by_id($order_id);
    
        //删除订单信息
        $flag = $model->table("order")->where("id=$order_id")->delete();
    
        //删除订单商品信息
        $flag2 = $model->table("order_goods")->where("order_id=$order_id")->delete();
    
        //记录操作日志
        $order_nos = $order_obj['order_no'];
    
        $user_obj = Common::get_user_obj($order_obj['user_id']);
    
        //         $info = array('status'=>'fail','msg'=>$flag."-".$flag2);
        //         echo Common::_toJSON($info);
        //         die;
    
        if($flag && $flag2)
        {
            Log::op($user_obj['name'],"删除订单",$user_obj['name'].":删除了订单 ".$order_nos);
            $model->query("commit");
            
             $msg = array('success','成功删除了订单：'.$order_nos);
             
            
            //$info = array('status'=>'success','msg'=>'操作成功！');
        }
        else
        {
            $model->query("rollback");
            $msg = array('error','操作失败');
           // $info = array('status'=>'fail','msg'=>'操作失败！');
        }
        $this->redirect("/ucenter/order",true,array('msg'=>$msg));
    }
    
    
    
    
}
